package org.douxiaoban.client.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.mobclick.android.MobclickAgent;
import org.douxiaoban.client.R;
import org.douxiaoban.client.app.App;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.widget.PopupRecommend;

import java.net.MalformedURLException;
import java.net.URL;


/**
 * Created by IntelliJ IDEA.
 * User: huangzhongkun
 * Date: 11-6-18
 * Time: 下午9:40
 */
public class NormalLoginActivity extends Activity {
    private static final int LOAD_CAPCHAID_DONE = 199;
    private static final int LOAD_CAPCHEID_FAIL = 200;

    private EditText _uname_edit;
    private EditText _passwd_edit;
    private EditText _capchaid_edit;
    private ImageView _capchaid_image;
    private TextView _load_capchaid_tx;
    private TextView _oauth_tx;
    private TextView _signup_tx;
    private Bitmap _capchaid_bitmap;
    private Button _submit_btn;
    private String _capchaid;
    private ProgressDialog _progress_dialog;
    private PopupRecommend _popup;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.pwlogin);

        setupView();
        setupListener();
        new ThreadLoadingCapcheid(_handler).start();
    }


    private void setupView(){
        _progress_dialog = new ProgressDialog(this);
        _progress_dialog.setIndeterminate(true);
        _progress_dialog.setCancelable(true);

        _uname_edit = (EditText)findViewById(R.id.login_username_edit);
        _uname_edit.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
        _passwd_edit = (EditText)findViewById(R.id.login_passwd_edit);
         _capchaid_edit = (EditText)findViewById(R.id.login_capchaid_edit);
        //close sugggestion
        _capchaid_edit.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
        _capchaid_image = (ImageView)findViewById(R.id.login_capchaid_img);
        _load_capchaid_tx = (TextView)findViewById(R.id.login_loading_capchaid_tx);
        _submit_btn = (Button)findViewById(R.id.login_submit_btn);
        _signup_tx = (TextView)findViewById(R.id.login_signup_douban);
        _oauth_tx = (TextView)findViewById(R.id.login_goto_oauth_tx);

        _popup = new PopupRecommend(this);

    }

    class ThreadLoadingCapcheid extends Thread{
        private Handler handler;

        public ThreadLoadingCapcheid(Handler h){
            this.handler = h;
         }

        @Override
        public void run() {
           _capchaid=  App.getDouanApiInstance().getCaptchaId();
           _capchaid_bitmap =App.getDouanApiInstance().getCaptchaImg(_capchaid);
           if(_capchaid_bitmap!=null){
               sendMessage(handler,LOAD_CAPCHAID_DONE,null);
           }else{
               sendMessage(handler,LOAD_CAPCHEID_FAIL,null);
           }

        }
    }

    private Handler _handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
               case LOAD_CAPCHAID_DONE:
                   changeCapChaIdImage();
                   break;
               case Assistant.LOGIN_SUCCESS:
                   _progress_dialog.dismiss();
                   saveAccessToken();

                   Intent i = new Intent(NormalLoginActivity.this,
                           NavigationActivity.class);
                   i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                   startActivity(i);
                   finish();
                   break;
               case Assistant.LOGIN_FAIL:
                   _progress_dialog.dismiss();
                   _popup.showToastWindow(Assistant.POPUP_FAIL_MESSAGE,
                           getString(R.string.login_fail_message));
                   new ThreadLoadingCapcheid(this).start();
                   break;
            }
        }
    };

    private void saveAccessToken(){
        SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(this);

        shared.edit().putString(Assistant.SETTING_ACCESS_TOKEN_KEY,App.
                getDouanApiInstance().ACCESS_TOKEN).commit();
        shared.edit().putString(Assistant.SETTING_ACCESS_TOKEN_SECRET,
                App.getDouanApiInstance().ACCESS_SECRET).commit();
        shared.edit().putString(Assistant.SETTING_UID,App.userId).commit();
        shared.edit().putString(Assistant.SETTING_UNAME,App.username).commit();

      }

    private void changeCapChaIdImage(){
        _load_capchaid_tx.setVisibility(View.GONE);
        _capchaid_image.setVisibility(View.VISIBLE);
        _capchaid_image.setImageBitmap(_capchaid_bitmap);
    }

    private void setupListener(){
        _oauth_tx.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(NormalLoginActivity.this,LoginActivity.class);
                startActivity(intent);
            }
        });

        _signup_tx.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                     Uri uri = Uri.parse(Assistant.SIGNUP_DOUBAN_URL);
                    Intent signupIntent = new Intent(Intent.ACTION_VIEW,uri);
                    startActivity(signupIntent);
            }

        });

        _submit_btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {

                final String  passwd = _passwd_edit.getText().toString();
                final String uname = _uname_edit.getText().toString();
                final String capchaid_value = _capchaid_edit.getText().toString();


                if(uname==null||uname.equals("")){
                    _popup.showToastWindow(Assistant.POPUP_FAIL_MESSAGE,
                            getString(R.string.login_no_uname));
                    return;
                }

                  if(passwd==null||passwd.equals("")){
                    _popup.showToastWindow(Assistant.POPUP_FAIL_MESSAGE,
                            getString(R.string.login_no_passwd));
                    return;
                }

                if(capchaid_value==null||capchaid_value.equals("")){
                    _popup.showToastWindow(Assistant.POPUP_FAIL_MESSAGE,
                            getString(R.string.login_no_capchaid));
                    return;
                }

                _progress_dialog.setMessage(getString(R.string.login_now));
                _progress_dialog.show();

                new Thread(){
                    @Override
                    public void run() {
                        Looper.prepare();
                        Boolean login_status = false;
                         try {
                         login_status = App.getDouanApiInstance().
                                 doubanLogin(uname, passwd, _capchaid, capchaid_value);
                           } catch (Exception e) {
                            e.printStackTrace();
                          }

                        Message message = new Message();

                        if(login_status)
                            message.what = Assistant.LOGIN_SUCCESS;
                         else
                            message.what = Assistant.LOGIN_FAIL;


                         _handler.handleMessage(message);
                         Looper.loop();
                    }
                }.start();

            }
        });
    }


    /**
       * 将线程中获取到的数据,存入Message中，并通过handler与UI线程通信
       *
       * @param handler
       * @param msg
       * @param data
       */
      public void sendMessage(Handler handler, int msg, Bundle data) {
          if (handler == null)
              return;

          Message message = new Message();
          message.what = msg;
          message.setData(data);
          handler.sendMessage(message);
      }

    @Override
    protected void onResume() {
        MobclickAgent.onResume(this);
        super.onResume();    //Super Method super.onResume();
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPause(this);
        super.onPause();    //Super Method super.onPause();
    }

}